package org.cloud.admin.auth.service.impl;

import java.util.Arrays;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.cloud.admin.auth.holder.AppHolder;
import org.cloud.admin.auth.service.SysRoleMenuService;
import org.cloud.admin.auth.service.SysRoleService;
import org.cloud.admin.auth.service.SysUserRoleService;
import org.cloud.module.common.dao.SysRoleDao;
import org.cloud.module.common.entity.SysRoleEntity;
import org.cloud.module.common.entity.SysUserEntity;
import org.cloud.module.common.model.Query;
import org.cloud.module.common.util.PageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 角色
 * @author wangyuan
 * @since 2019年6月26日 下午11:16:02
 *
 */
@Service("sysRoleService")
public class SysRoleServiceImpl extends ServiceImpl<SysRoleDao, SysRoleEntity> implements SysRoleService {
	
	@Autowired
	private SysRoleMenuService sysRoleMenuService;
	
    @Autowired
    private SysUserRoleService sysUserRoleService;

	@Override
	public PageUtils queryPage(Map<String, Object> params) {
		String roleName = (String)params.get("roleName");
		
		IPage<SysRoleEntity> page = new Query<SysRoleEntity>().getPage(params);
        
        QueryWrapper<SysRoleEntity> queryWrapper = new QueryWrapper<>();
        
        queryWrapper.select("id", "role_name", "remark", "created_time");
        
        queryWrapper.like(StringUtils.isNotBlank(roleName),"role_name", roleName);

        page = this.page(page, queryWrapper);
        
        return new PageUtils(page);
	}

    @Override
    public void saveRole(SysRoleEntity role) {
        this.save(role);

        //保存角色与菜单关系
        sysRoleMenuService.saveOrUpdate(role.getId(), role.getMenuIdList());
    }

    @Override
    public void update(SysRoleEntity role) {
        SysRoleEntity oldRole = getById(role.getId());
        oldRole.setRoleName(role.getRoleName());
        oldRole.setRemark(role.getRemark());
        oldRole.setUpdatedUser(String.valueOf(AppHolder.getLoginedUserId()));
        
        this.updateById(role);

        //更新角色与菜单关系
        sysRoleMenuService.saveOrUpdate(role.getId(), role.getMenuIdList());
    }

    @Override
    public void deleteBatch(Long[] roleIds) {
        //删除角色
        this.removeByIds(Arrays.asList(roleIds));

        //删除角色与菜单关联
        sysRoleMenuService.deleteBatch(roleIds);

        //删除角色与用户关联
        sysUserRoleService.deleteBatch(roleIds);
    }
}
